
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gun/event/inventory_event.dart';
import 'package:gun/http/api.dart';
import '../entity/book_entity.dart';
import '../main.dart';
import '../widget/dialog.dart';

class Move extends StatefulWidget {
  const Move({Key? key}) : super(key: key);

  @override
  State<Move> createState() => _MoveState();
}

class _MoveState extends State<Move> {

  RxnString floor = RxnString();
  String? placeNo;
  RxnString toFloor = RxnString();
  String? toPlaceNo;
  RxInt count = RxInt(0);
  RxList<BookEntity> bookList = RxList();
  RxBool hasMove = RxBool(false);

  StreamSubscription? subscription;

  @override
  initState() {
    super.initState();
    subscription = eventFactory.on<InventoryEvent>().listen((event) {
      _analyze(event.data);
    });
    player.play('audio/scan_floor_from.mp3');
  }


  @override
  void dispose() {
    subscription?.cancel();
    subscription = null;
    super.dispose();
  }

  _analyze(String epc){
    if(placeNo == null){
      if(epc.startsWith('B0')){
        try{
          var length = int.parse(epc.substring(2,4));
          placeNo = epc.substring(4,4+length);
          _findPlace(placeNo);

          return;
        }catch(e){
          print(e);
        }
      }
      return;
    }
    if(toPlaceNo == null && floor.value != null){
      if(epc.startsWith('B0')){
        try{
          var length = int.parse(epc.substring(2,4));
          var no = epc.substring(4,4+length);
          if(no != placeNo){
            toPlaceNo = no;
            _findPlace(toPlaceNo);
          }
          return;
        }catch(e){
          print(e);
        }
      }
      return;
    }
  }


  _findPlace(no) async {
    var name = await findPlace(no);
    if(name != null){
      if(floor.value == null){
        floor.value = name;
        player.play('audio/scan_floor_to.mp3');
        return;
      }
      if(toFloor.value == null){
        toFloor.value = name;
        _findRfidBooks(placeNo);
        return;
      }
    }else{
      if(floor.value == null){
        placeNo = null;
        return;
      }
      if(toFloor.value == null){
        toPlaceNo = null;
        return;
      }
    }
  }

  _findRfidBooks(no) async {
    var books = await findRfidPlaceBook(no);
    if(books!=null) {
      bookList.addAll(books);
      count.value = bookList.length;
    }
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 30.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                Get.back();
              },
              child: Row(
                children: [
                  const Icon(Icons.arrow_back_ios_new,color: Colors.white,),
                  Text("返回",style: TextStyle(color: Colors.white,fontSize: 16.sp),)
                ],
              )
            ),
            Image.asset("assets/images/move_title.png",width: 100.w,fit: BoxFit.fitWidth,),
            InkWell(
              onTap: (){
                DialogWidget().settingDialog();
              },
              child: Text("调整功率",style: TextStyle(color: Colors.white,fontSize: 16.sp),),
            )
          ],
        )
    );
  }


  _count(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text("移架数据",style: TextStyle(color: Colors.white,fontSize: 22.sp,fontWeight: FontWeight.bold),),
        Row(
          children: [
            Text("待移架数量：",style: TextStyle(color: Colors.white,fontSize: 16.sp),),
            Obx(() => Text("${count.value}",style: TextStyle(color: Colors.white,fontSize: 16.sp),))
          ],
        )
      ],

    );
  }

  _info(){
    return Container(
      width: double.infinity,
      height: 95.h,
      margin: EdgeInsets.only(top: 10.r),
      padding: EdgeInsets.all(16.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Image.asset("assets/images/icon_floor.png",width: 20.w,fit: BoxFit.fitWidth,),
              Text(" 层架信息：",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
            ],
          ),
          Obx(() => Text(floor.value??'',maxLines:2,style: TextStyle(color: Colors.black,fontSize: 16.sp),)),
          Obx(() => Text(toFloor.value != null?'to ${toFloor.value}':'',maxLines:2,style: TextStyle(color: const Color.fromARGB(255, 20, 196, 196),fontSize: 16.sp),)),

        ],
      ),
    );
  }

  _scanFloorExample(msg){
    return SizedBox(
      height: 420.h,
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Image.asset("assets/images/scan_floor.png",width: 340.w,fit: BoxFit.fitWidth,),
          Positioned(
            top: 210.h,
            right: 0,
            child: Image.asset("assets/images/gun.gif",width: 180.w,fit: BoxFit.fitWidth,),
          ),
          Positioned(
              top: 320.h,
              child: Text(msg,style: TextStyle(color: Colors.white,fontSize: 22.sp,fontWeight: FontWeight.bold),)
          )

        ],
      )
    );
  }

  _empty(){
    return SizedBox(
        height: 420.h,
        child: Column(
          children: [
            SizedBox(height: 40.h,),
            Image.asset("assets/images/move_empty.png",width: 220.w,fit: BoxFit.fitWidth,),
            SizedBox(height: 60.h,),
            InkWell(
              onTap: (){
                floor.value = null;
                toFloor.value = null;
                placeNo = null;
                toPlaceNo = null;
                count.value = 0;
                bookList.clear();
                hasMove.value = false;
                player.play('audio/scan_floor_from.mp3');
              },
              child: Image.asset("assets/images/move_next.png",width: 140.w,fit: BoxFit.fitWidth,),
            ),
          ],
        )
    );
  }

  _list(){
    return Obx(() => Container(
      height: 330.h,
      margin: EdgeInsets.only(bottom: 10.r),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _listItem(index);
        },
        itemCount: bookList.length,
      )
    ));
  }

  _listItem(index){
    var item = bookList[index];
    return Container(
      margin: EdgeInsets.only(top: 10.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      padding: EdgeInsets.all(10.r),
      child: Column(
        children: [
          InkWell(
            onTap: (){
              var index = bookList.indexOf(item);
              bookList.removeAt(index);
              item.expand = !item.expand;
              bookList.insert(index, item);
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 230.w,child:Text('${item.mainTitle}'),),
                Container(
                    width: 70.w,
                    height: 30.h,
                    margin: EdgeInsets.only(left: 10.r),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: item.stackStatus==0?Colors.blue:item.stackStatus==1?const Color.fromARGB(255, 20, 196, 196):Colors.red,
                      borderRadius: BorderRadius.all(Radius.circular(6.r)),
                    ),
                    child: Text(item.stackStatus==0?'待移架':item.stackStatus==1?'已移架':'未移架',style: const TextStyle(color: Colors.white),)
                ),
                Icon(item.expand?Icons.keyboard_arrow_up_rounded:Icons.keyboard_arrow_down_rounded,color: Colors.grey,)
              ],
            ),
          ),
          if(item.expand)...
            [
              Column(
                children: [
                  SizedBox(height: 6.h,),
                  Divider(height: 0.5.h, indent: 4.w, endIndent: 4.w, color: const Color.fromRGBO(86, 169, 255, 1),),
                  SizedBox(height: 6.h,),
                  Row(
                    children: [
                      const Text('存放位置：'),
                      Text('${item.placeName}',style: const TextStyle(color: Color.fromARGB(255, 20, 196, 196)),),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('条码号：${item.no}'),
                      Text('索书号：${item.searchNo}'),
                    ],
                  )
                ],
              )
            ]
        ],
      )
    );
  }

  _action(){
    return Obx(() => Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        hasMove.value?
          InkWell(
            onTap: (){
             Get.back();
            },
            child: Image.asset("assets/images/move_done.png",width: 140.w,fit: BoxFit.fitWidth,),
          ):
          InkWell(
            onTap: (){
              floor.value = null;
              toFloor.value = null;
              placeNo = null;
              toPlaceNo = null;
              count.value = 0;
              bookList.clear();
              hasMove.value = false;
              player.play('audio/scan_floor_from.mp3');
              },
            child: Image.asset("assets/images/clear_btn.png",width: 140.w,fit: BoxFit.fitWidth,),
          ),
        hasMove.value?
          InkWell(
            onTap: ()  {
              floor.value = null;
              toFloor.value = null;
              placeNo = null;
              toPlaceNo = null;
              count.value = 0;
              bookList.clear();
              hasMove.value = false;
              player.play('audio/scan_floor_from.mp3');
            },
            child: Image.asset("assets/images/move_next.png",width: 140.w,fit: BoxFit.fitWidth,),
          ):
          InkWell(
            onTap: () async {
              var result = await move(placeNo,toPlaceNo, bookList.map((element) => element.no).join(','));
              for (var item in bookList) {
                var index = bookList.indexOf(item);
                bookList.removeAt(index);
                item.stackStatus = result?1:-1;
                bookList.insert(index, item);
                hasMove.value = true;
              }
              player.play(result?'audio/success.mp3':'audio/failed.mp3');

            },
            child: Image.asset("assets/images/move_btn.png",width: 140.w,fit: BoxFit.fitWidth,),
          ),
      ],
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(left: 20.r,right: 20.r),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _title(),
            SizedBox(height: 30.h,),
            _count(),
            _info(),
            Obx(() => floor.value == null?_scanFloorExample('请扫描待移架的层架标签'):
                      toFloor.value == null?_scanFloorExample('请扫描确认移架的层架标签')
                          :count.value == 0?_empty()
                          :_list()),
            Obx(() => Visibility(visible:count.value > 0,child: _action(),))
          ],
        )
      ),
    );
  }
}